// pages/index/detailsSW/index.js
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import {
	clearAlertRefresh
} from '../../../../utils/hooks';

const $api = require('../../../../request/api').API;
const app = getApp();
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		useId: '', // 使用人的d
		userName: '', // 使用人的名称
		actualUserId: '',
		flowEndDate: '',
		activeDate: '',
		siteRate:'',
		id: '',
		// 住户id
		houseId: '',
		// 呼叫器id
		beeperId: '',
		// 设备id
		equipId: '',
		equipMac: '',
		//--------------------------------------------------------------
		wifiName: '',
		wifiPwd: '',
		linkName: '',
		phone: '',
		address: '',
		provinceName: '',
		cityName: '',
		areaName: '',
		streetName: '',
		villageName: '',
		callingName: '',
		callingStatus: 0,
		callingErrorStatus: 0,
		equipNickName: '',
		installArea: '',
		equipCode: '',
		money: 0,
		showModifyUser: false,
		userList: [],
		// 标签列表
		tagList: [{
			beeperTagId: '1',
			tagName: '帅气'
		}],
		createDate: '',
		//-----------------------------------------------------------------
		// 设置wifi弹框
		showWifiOverlay: false,
		// 设置新增标签弹框
		showTagOverlay: false,
		// 点击标签分类显示
		selectClassShow: false,
		selectClassName: '点击选择分类',
		selectClassId: '',
		tagClass: [],
		// 是否为主用户
		mainFlag: 0,
		// 修改昵称或者安装区域弹框
		showUpdateData: false,
		showType: 1, //1代表昵称修改 2代表安装区域修改
		tempData: '', //临时数据，用来修改昵称和安装区域
		showRecord: false, // 过往记录弹窗控制
		active: 0, // 过往记录tab
		activeList: ['体温', '心率', '血氧', '血压'],
		tabsIcon: [
			'https://pic.kanglailab.com/common/temperature.png',
			'https://pic.kanglailab.com/common/bloodPressure.png',
			'https://pic.kanglailab.com/common/equip/oxygen.png',
			'https://pic.kanglailab.com/common/heart_rate.png'
		], // 选项卡图标
		loadingRecord: false,
		historicalParams: {
			// 过往记录列表参数
			pageNo: 1,
			pageSize: 10,
			type: 1
		},
		latestDetectionData: {
			// 最新检测数据
			heart: '-',
			oxygen: '-',
			pressureMax: '-',
			pressureMin: '-',
			temp: '-'
		},
		pastRecordedData: [], // 过往记录数据
		pastRecordedTotal: 1,
		localeId: '',
		startDetectionShow: false,
		timeDetectionShow: false,
		detectionList: [{
				type: 1,
				name: '体温',
				flag: false,
				time: ''
			},
			{
				type: 2,
				name: '心率',
				flag: false,
				time: ''
			},
			{
				type: 3,
				name: '血氧',
				flag: false,
				time: ''
			},
			{
				type: 4,
				name: '血压',
				flag: false,
				time: ''
			},
		],
		timeColumns: [{
				name: "无",
				val: 0
			},
			{
				name: 0.5,
				val: 1800
			},
			{
				name: 1,
				val: 3600
			},
			{
				name: 2,
				val: 7200
			},
			{
				name: 3,
				val: 10800
			},
			{
				name: 4,
				val: 14400
			},
			{
				name: 5,
				val: 18000
			},
			{
				name: 6,
				val: 21600
			},
		],
		timeIndex: 0,
		markers: [{
			id: 1,
			longitude: 0,
			latitude: 0,
			width: 26,
			height: 30,
		}],
		markersInfo: {
			address: '',
			areaName: '',
			cityName: '',
			createDate: '',
		},
		frequencyShow: false,
		frequencyActions: [{
				name: '2分钟',
				value: 120
			},
			{
				name: '5分钟',
				value: 300
			},
			{
				name: '15分钟',
				value: 900
			},
			{
				name: '30分钟',
				value: 1800
			},
			{
				name: '1小时',
				value: 3600
			},
			{
				name: '2小时',
				value: 7200
			},
			{
				name: '3小时',
				value: 10800
			},
			{
				name: '5小时',
				value: 18000
			}
		]
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		let id = options.beeperId;
		if (id != undefined) {
			this.setData({
				id: id,
				localeId: options.localeId
			});
		}
	},

	// 请求数据
	getData(id) {
		let params = {
			id: this.data.id
		};
		let {
			userList
		} = this.data;
		$api
			.getBeeperSW(params)
			.then(res => {
				if (res.data.status == 0) {
					var data = res.data.data;
					this.setData({
							houseId: data.houseId,
							beeperId: data.beeperId,
							createDate: data.createDate,
							equipId: data.equipId,
							siteRate:data.siteRate,
							linkName: data.linkName,
							phone: data.phone,
							address: data.address == '待补充' ? '' : data.address,
							provinceName: data.provinceName,
							cityName: data.cityName,
							areaName: data.areaName,
							streetName: data.streetName,
							villageName: data.villageName,
							callingName: data.equipName,
							callingStatus: data.equipState,
							callingErrorStatus: data.errorState,
							money: data.balance,
							tagList: data.tags,
							mainFlag: data.mainFlag,
							equipNickName: data.equipNickName,
							installArea: data.installArea,
							equipCode: data.equipCode,
							equipMac: data.equipMac,
							activeDate: data.activeDate,
							flowEndDate: data.flowEndDate == null ? '' : data.flowEndDate,
							actualUserId: data.actualUserId,
							userName: userList.find(item => item.id == data.actualUserId)?.name
						},
						() => {
							this.FetchMonitoringData();
							this.getLocationData()
						}
					);
					if (this.data.address == '') {
						this.setData({
							showWifiOverlay: true
						});
					}
				}
			})
			.catch(err => {
				console.log(err);
			});
	},

	// 打开wifi设置弹框
	openSetWifi() {
		this.setData({
			showWifiOverlay: true,
			linkName: this.data.contact,
			phone: this.data.phone
		});
	},
	// 关闭wifi设置弹框
	closeSetWifi() {
		if (this.data.address == '') {
			// 不填信息退出，直接解绑并回到首页
			this.jiebang();
			setTimeout(() => {
				wx.switchTab({
					url: '/pages/equipment/index'
				});
			}, 500);
		} else {
			this.setData({
				showWifiOverlay: false
			});
		}
	},

	toDetail() {
		const {
			id,
			localeId
		} = this.data
		wx.navigateTo({
			url: '/subcontract/equipment/pages/detailsSW/index?beeperId=' + id + '&localeId=' + localeId
		});
	},

	onSelectClass(event) {
		console.log(event.detail);
		this.setData({
			selectClassName: event.detail.name,
			selectClassId: event.detail.id
		});
	},

	// 设置wifi
	setWIFI() {
		let params = {
			houseId: this.data.houseId,
			linkName: this.data.linkName,
			phone: this.data.phone,
			address: this.data.address,
			beeperId: this.data.beeperId
		};
		if (params.linkName == '') {
			Toast.fail('联系人不能为空');
			return;
		}
		if (params.phone == '') {
			Toast.fail('联系电话不能为空');
			return;
		}
		if (params.address == '') {
			Toast.fail('门牌号不能为空');
			return;
		}
		$api
			.setHouseWifi(params)
			.then(res => {
				console.log('设置wifi回调', res);
				if (res.data.status == 0) {
					wx.showToast({
						title: '设置地址信息成功'
					});
					this.setData({
						showWifiOverlay: false
					});
					this.getData(this.data.id);
				}
			})
			.catch(err => {
				console.log(err);
			});
	},
	// 跳转用户列表
	toWarningRecord() {
		console.log('equipId', this.data.equipId);
		wx.navigateTo({
			url: '../warningRecord/index?id=' + this.data.equipId
		});
	},
	// 解绑设备
	jiebang() {
		Dialog.confirm({
			title: '提示',
			message: '确认解绑当前设备吗？'
		}).then(ress => {
		 let params = {
			id: this.data.equipId
		};
		$api.unbindBinding(params).then(res => {
				console.log('解绑设备', res);
				if (res.data.status == 0) {
					wx.showToast({
						title: '解绑成功！'
					});
					setTimeout(() => {
						wx.switchTab({
							url: '/pages/equipment/index'
						});
					}, 1000);
				}
			})
			.catch(err => {
				console.log('解绑设备', err);
			});
		})
	},
	// 解除警报
	jieAlarm() {
		Dialog.confirm({
			title: '提示',
			showCancelButton: true,
			cancelButtonText: '误触发',
			confirmButtonText: '已处理',
			closeOnClickOverlay: true,
			message: '确定解除警报吗？'
		}).then(()=>{
			this.handleAlarmLiftedProcess()
		}).catch(()=>{
			this.handleFalseAlarmRelease()
		});
	},
	/**
	 * 解除警报 - 已处理
	 */
	handleAlarmLiftedProcess() {
		$api
			.equipAllClear({
				equipId: this.data.equipId,
				cancelReason: 2
			})
			.then(() => {
				wx.showToast({
					title: '解除成功！'
				});
				clearAlertRefresh(this.data.id, this);
			});
	},

	/**
	 * 解除警报 - 误触
	 */
	handleFalseAlarmRelease() {
		$api
			.equipAllClear({
				equipId: this.data.equipId,
				cancelReason: 1
			})
			.then(() => {
				wx.showToast({
					title: '解除成功！'
				});
				clearAlertRefresh(this.data.id, this);
			});
	},
	// 去设置紧急联系人
	toUrgentContact() {
		wx.navigateTo({
			url: '/subcontract/equipment/pages/urgentContact/index?equipId=' + this.data.equipId
		});
	},
	// 通讯录
	toAddressBook() {
		wx.navigateTo({
			url: '/subcontract/equipment/pages/addressBook/index?equipId=' + this.data.equipId + '&equipType=1'
		});
	},

	//开始检测
	startDetection(e) {
		const type = e.currentTarget.dataset.type
		if (type == 1) {
			this.setData({
				startDetectionshow: true
			})
		} else {
			const list = this.data.detectionList.filter(item => item.flag).map(item => item.type);
			if (list.length == 0) {
				Toast.fail("请选择需要检测的项目")
				return false
			}
			Toast.success('预计5-10分钟完成检测，请稍候查看数据')
			$api.startDetection({
				equipId: this.data.equipId,
				type: list.join(',')
			}).then(res => {

			})
			this.detectionClose()
		}
	},

	//定时检测
	timingDetection(e) {
		const type = e.currentTarget.dataset.type
		let list = this.data.detectionList
		if (type == 1) {
			$api.getDetectionData({
				equipId: this.data.equipId
			}).then(res => {
				if (res.data.status == 0) {
					let timearr = res.data.data.split(",")
					for (let i = 0; i < 4; i++) {
						list[i].time = timearr[i] == "0" ? "无" : timearr[i];
					}
					this.setData({
						detectionList: list
					})
				}
			})
			this.setData({
				timeDetectionshow: true
			})
		} else if (type == 2) {
			let arr = []
			for (let i in list) {
				arr.push((list[i].time == '无' || list[i].time == false ? 0 : list[i].time))
			}
			Toast.loading({
				duration: 0, // 持续展示 toast
				forbidClick: true,
				message: '请等待...',
			});
			$api.timingDetection({
				equipId: this.data.equipId,
				checkRate: arr.join(',')
			}).then(res => {
				if (res.data.status == 0) {
					Toast.clear()
					Toast.success('操作成功')
					this.timeDetectionClose()
				} else {
					Toast.clear()
					Toast.fail(res.data.msg)
				}
			})
		} else {
			list[this.data.timeIndex].time = e.detail.val
			this.setData({
				detectionList: list
			})
		}
	},
	//立即检测关闭
	detectionClose() {
		let detectionList = this.data.detectionList.map(item => {
			return {
				...item,
				flag: false
			};
		});
		this.setData({
			startDetectionshow: false,
			detectionList
		})
	},
	//定时检测关闭
	timeDetectionClose() {
		let detectionList = this.data.detectionList.map(item => {
			return {
				...item,
				flag: false,
				time: ''
			};
		});
		this.setData({
			timeDetectionshow: false,
			detectionList
		})
	},
	detectionChange(event) {
		let item = event.currentTarget.dataset.item
		let index = event.currentTarget.dataset.index
		item.flag = !item.flag
		let detectionList = this.data.detectionList
		detectionList[index] = item
		this.setData({
			detectionList
		})
	},
	openTimeSelect(e) {
		this.setData({
			timeIndex: e.currentTarget.dataset.index,
			timeValShow: !this.data.timeValShow,
		})
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	async onShow() {
		await this.getUserList();
		this.getData(this.data.id);
	},

	// 输入框绑定值
	wifiNameInput(e) {
		let value = e.detail.value;
		this.setData({
			wifiName: value
		});
	},
	wifiPwdInput(e) {
		let value = e.detail.value;
		this.setData({
			wifiPwd: value
		});
	},
	contactInput(e) {
		let value = e.detail.value;
		this.setData({
			linkName: value
		});
	},
	phoneInput(e) {
		let value = e.detail.value;
		this.setData({
			phone: value
		});
	},
	addressInput(e) {
		let value = e.detail.value;
		this.setData({
			address: value
		});
	},
	tagNameInput(e) {
		let value = e.detail.value;
		this.setData({
			addTagName: value
		});
	},
	// 打开修改昵称弹框
	openUpdateData(e) {
		let type = e.currentTarget.dataset.type;
		this.setData({
			showUpdateData: true,
			showType: type,
			tempData: type == 1 ? this.data.equipNickName : this.data.installArea
		});
	},
	// 关闭修改昵称弹框
	closeUpdateData() {
		this.setData({
			showUpdateData: false
		});
	},
	// 输入绑定
	dataInput(e) {
		let value = e.detail.value;
		this.setData({
			tempData: value
		});
	},
	// 修改昵称
	UpdateData() {
		if (!this.data.tempData && this.data.showType == 1) {
			Toast('请输入昵称');
			return;
		} else if (!this.data.tempData && this.data.showType == 2) {
			Toast('请输入安装区域');
			return;
		}
		let params = {
			id: this.data.equipId,
			name: this.data.tempData,
			state: this.data.showType
		};
		$api
			.UpdataName(params)
			.then(res => {
				if (res.data.status == 0) {
					if (this.data.showType == 1) {
						wx.showToast({
							title: '设置昵称成功'
						});
					} else {
						wx.showToast({
							title: '设置成功'
						});
					}

					this.setData({
						showUpdateData: false
					});
					this.getData(this.data.id);
				}
			})
			.catch(err => {
				console.log(err);
			});
	},

	/**
	 * 今日检测数据
	 * @constructor
	 */
	FetchMonitoringData() {
		const {
			equipId
		} = this.data;
		$api
			.EquipTodayLog({
				equipId
			})
			.then(res => {
				const {
					data
				} = res.data;
				this.setData({
					latestDetectionData: {
						...data,
						temp: data.temp ? data.temp + '℃' : '-',
						heart: data.heart ? data.heart + 'bpm' : '-',
						oxygen: data.oxygen ? data.oxygen + 'spo2' : '-',
						pressureMin: data.pressureMin ? data.pressureMin + 'mmHg' : '-',
						pressureMax: data.pressureMax ? data.pressureMax + 'mmHg' : '-'
					}
				});
			});
	},

	/**
	 * 请求过往数据列表
	 */
	FetchLoadHistoricalData() {
		const params = {
			equipId: this.data.equipId,
			...this.data.historicalParams
		};
		$api
			.EquipLogPage(params)
			.then(res => {
				this.setData({
					loadingRecord: false
				});
				const {
					data
				} = res.data;
				this.setData({
					pastRecordedTotal: data.totalPage,
					pastRecordedData: this.data.pastRecordedData.concat(
						data.list.map(i => {
							if (params.type === 1) {
								return {
									...i,
									value: i.temp + '℃'
								};
							}
							if (params.type === 2) {
								return {
									...i,
									value: i.heart + 'bpm'
								};
							}
							if (params.type === 3) {
								return {
									...i,
									value: i.oxygen + 'spo2'
								};
							}
							if (params.type === 4) {
								return {
									...i,
									value: `${i.pressureMin}mmHg - ${i.pressureMax}mmHg`
								};
							}
						})
					)
				});
			})
			.catch(() => {
				this.setData({
					loadingRecord: false
				});
			});
	},

	/**
	 * 打开历史检测弹框
	 */
	handleHistoricalDetectionClick() {
		this.setData({
			showRecord: true,
			loadingRecord: true
		});
		this.FetchLoadHistoricalData();
	},

	/**
	 * 关闭历史记录弹窗
	 */
	handleHistoricalDetectionClose() {
		this.setData({
			showRecord: false,
			loadingRecord: false,
			pastRecordedData: [],
			historicalParams: {
				pageNo: 1,
				pageSize: 10,
				type: 1
			}
		});
	},

	/**
	 * 过往记录tab change
	 */
	handleHistoricalTableChange(event) {
		this.setData({
				loadingRecord: true,
				historicalParams: {
					...this.data.historicalParams,
					type: event.detail.index + 1,
					pageNo: 1
				},
				pastRecordedData: []
			},
			() => {
				this.FetchLoadHistoricalData();
			}
		);
	},

	/**
	 * 监听记录划到底部，加载数据
	 */
	handleHistoricalScrollToLower() {
		// 如果正在加载数据或已经到达最后一页，则不再请求
		if (this.data.pageNo === this.data.pastRecordedTotal) {
			return;
		}
		this.setData({
				historicalParams: {
					...this.data.historicalParams,
					pageNo: this.data.historicalParams.pageNo + 1
				}
			},
			() => {
				this.FetchLoadHistoricalData();
			}
		);
	},
	// 获取产所下的用户
	async getUserList() {
		let res = await $api.listUserCustomer({
			localeId: this.data.localeId
		});
		this.setData({
			userList: res.data.data || []
		});
	},
	// 显示用户弹框
	async showModifyUserPopup() {
		this.setData({
			showModifyUser: true
		});
	},
	// 关闭用户选择弹框
	closeMoidfyUserPopup() {
		this.setData({
			showModifyUser: false
		});
	},
	// 确定使用人
	async confirmModifyUser(e) {
		const {
			id,
			name
		} = e.detail.value;
		const params = {
			deviceId: this.data.equipId,
			userId: id
		};
		await $api.updateSugarUser(params);
		Toast.success('修改成功');
		this.setData({
			showModifyUser: false,
			actualUserId: id,
			userName: name
		});
	},

	//立即定位
	openLocation() {
		const params = {
			equipId: this.data.equipId
		};
		$api.openLocation(params).then(res => {
			if (res.data.status == 0) {
				Toast.success('操作成功')
				this.getLocationData();
			} else {
				Toast.fail(res.data.msg)
			}
		}).catch(err => {
			Toast.fail(err.msg)
		});
	},

	//获取最新一条定位数据
	getLocationData() {
		const params = {
			equipId: this.data.equipId
		};
		$api.getFootprint(params).then(res => {
			if(res.data.data!=null){
				const {
					latitude,
					longitude,
					address,
					areaName,
					cityName,
					createDate
				} = res.data.data;
				this.setData({
					'markers[0].latitude': Number(latitude),
					'markers[0].longitude': Number(longitude),
					'markersInfo.address': address,
					'markersInfo.areaName': areaName,
					'markersInfo.cityName': cityName,
					'markersInfo.createDate': createDate,
				});
			}
		});
	},

	//定位频率
	frequencySet() {
		this.setData({
			frequencyShow: true
		})
	},

	frequencyClose() {
		this.setData({
			frequencyShow: false
		})
	},

	frequencySelect(event) {
		$api.setFrequency({
			equipId: this.data.equipId,
			siteRate: event.detail.value
		}).then(res => {
			if (res.data.status == 0) {
				Toast.success('操作成功')
				this.getLocationData();
				this.getData()
			} else {
				Toast.fail(res.data.msg)
			}
		}).catch(err => {
			Toast.fail(err.msg)
		})
	},

	//查看足迹
	viewFootprint() {
		wx.navigateTo({
			url: '/subcontract/equipment/pages/viewFootprint/index?equipId=' + this.data.equipId,
		})
	},
});